/**
 *
 * @param {*} time -需要格式化的时间，可以被new Date()解析的时间格式即可
 * @param {String} format -时间格式，如"Y-M-D h:m:s",将会格式化为2020-10-15 15:09:58，此参数可以为空，为空的话，会被格式化为多久前，如20分钟前,距离30天以上的时间会展示日期
 */
function formatTime(time, format) {
  if (typeof time === 'string') {
    time = time.replace(/-/g, '/')
  }
  function formatNumber(n) {
    n = n.toString()
    return n[1] ? n : '0' + n
  }

  function getDate(time, format) {
    const formateArr = ['Y', 'M', 'D', 'h', 'm', 's']
    const returnArr = []
    const date = new Date(time)
    returnArr.push(date.getFullYear())
    returnArr.push(formatNumber(date.getMonth() + 1))
    returnArr.push(formatNumber(date.getDate()))
    returnArr.push(formatNumber(date.getHours()))
    returnArr.push(formatNumber(date.getMinutes()))
    returnArr.push(formatNumber(date.getSeconds()))
    for (const i in returnArr) {
      format = format.replace(formateArr[i], returnArr[i])
    }
    return format
  }

  function getDateDiff(time) {
    let r = ''
    const ft = new Date(time)
    const nt = new Date()
    const nd = new Date(nt)
    nd.setHours(23)
    nd.setMinutes(59)
    nd.setSeconds(59)
    nd.setMilliseconds(999)
    const d = Math.floor((nd - ft) / 86400000)

    switch (true) {
      case d === 0:
        // eslint-disable-next-line no-case-declarations
        const t = Math.floor(nt / 1000) - Math.floor(ft / 1000)
        switch (true) {
          case t < 60:
            r = '刚刚'
            break
          case t < 3600:
            r = Math.floor(t / 60) + '分钟前'
            break
          default:
            r = Math.floor(t / 3600) + '小时前'
        }
        break
      case d === 1:
        r = '昨天'
        break
      case d === 2:
        r = '前天'
        break
      case d > 2 && d < 30:
        r = d + '天前'
        break
      default:
        r = getDate(time, 'Y-M-D')
    }
    return r
  }
  if (!format) {
    return getDateDiff(time)
  } else {
    return getDate(time, format)
  }
}
export default formatTime
